<template>
  <div class="freeCountdown" v-if="!isCountdownDone">
    <!-- 背景:英语+越南 -->
    <img
      v-if="globalStore.$state.language == 'pt'"
      class="freeCountdown-bg"
      src="/image/lottery-v3/yy-chest-enter3.png"
    />
    <img
      v-else-if="globalStore.$state.language == 'mys'"
      class="freeCountdown-bg"
      src="/image/lottery-v3/yy-chest-enter2.png"
    />
    <img
      v-else-if="globalStore.$state.language == 'indonesia'"
      class="freeCountdown-bg"
      src="/image/lottery-v3/yy-chest-enter1.png"
    />
    <img
      v-else
      class="freeCountdown-bg"
      src="/image/lottery-v3/yy-chest-enter.png"
    />
    <!-- 倒计时 + 领取 -->
    <div class="content items-center">
      <!-- 领取 -->
      <div
        v-if="isShowClaimEnd"
        class="content-receive"
        :class="{
          'content-languagePt': globalStore.$state.language == 'pt',
        }"
      >
        {{ $t("lotteryMoney.receive") }}
      </div>
      <!-- 倒计时 -->
      <div
        v-else
        class="content-countdown items-center"
        :class="{
          'content-languagePt': globalStore.$state.language == 'pt',
        }"
      >
        <div
          class="content-countdown-text content-countdown-width"
          style="margin-left: 0px"
        >
          {{ hours }}
        </div>
        <div class="content-countdown-point">:</div>
        <div class="content-countdown-text content-countdown-width">
          {{ minutes }}
        </div>
        <div class="content-countdown-point">:</div>
        <div class="content-countdown-text content-countdown-width">
          {{ seconds }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="freeCountdown">
import { useEventBus } from "@vueuse/core";
import { useGlobalStore } from "~~/store/global";
import { useLotteryV3Store } from "~/store/modules/lottery-v3";

const emit = defineEmits(["countdownDone"]);
const globalStore = useGlobalStore();

const lotteryStore = useLotteryV3Store();

// 未开始倒计时
let unsubscribeFns: any = {}; // 执行的函数数组
let hours = ref("--");
let minutes = ref("--");
let seconds = ref("--");
const isCountdownDone = ref(false); // 倒计时,是否结束
// 设置倒计时结束时间
let endTime = Number(lotteryStore.$state.chestWlSource.endTime || 0); // 默认: recordStatus == 2 的结束时间
function updateLotteryCountdown() {
  if (!lotteryStore.$state.chestWlSource.recordStatus) return;
  // 倒计时结束通知一次
  let isRefrrsh = false;
  // 计算函数
  const updateCountdown = (now: any) => {
    if (Number(endTime) <= 0) return;
    const distance = endTime - Number(now);
    // 1. 倒计时结束时的处理
    if (distance < 0 && !isRefrrsh) {
      isRefrrsh = true;
      setTimeout(() => {
        isCountdownDone.value = true;
        emit("countdownDone");
      }, 500);
      return;
    }
    // 2. 计算剩余的小时、分钟和秒
    if (distance >= 0) {
      hours.value = `${Math.floor(
        (distance % (1000 * 60 * 60 * 24 * 7)) / (1000 * 60 * 60)
      )}`;
      if (Number(hours.value) < 10) hours.value = `0${hours.value}`;
      minutes.value = `${Math.floor(
        (distance % (1000 * 60 * 60)) / (1000 * 60)
      )}`;
      if (Number(minutes.value) < 10) minutes.value = `0${minutes.value}`;
      seconds.value = `${Math.floor((distance % (1000 * 60)) / 1000)}`;
      if (Number(seconds.value) < 10) seconds.value = `0${seconds.value}`;
    }
  };

  // 3. 先执行一次,不然要等一秒才能计算
  const ckbzTime = new Date("2024/01/01").getTime();
  if (Number(globalStore.$state.serverTime) > ckbzTime) {
    updateCountdown(globalStore.$state.serverTime);
  }

  // 4. 定时执行
  unsubscribeFns["updateLotteryCountdown"] = (val: number) => {
    updateCountdown(val);
  };
}

// 监听状态变化
const isShowClaimEnd = ref(false);
const recordStatus_watch = watch(
  () => lotteryStore.$state.chestWlSource.recordStatus,
  (newVal) => {
    if (newVal) {
      if (newVal == 2) {
        // 设置倒计时
        endTime = Number(lotteryStore.$state.chestWlSource.endTime || 0);
      } else if (newVal == 3) {
        isShowClaimEnd.value = true;
        endTime = Number(lotteryStore.$state.chestWlSource.claimEndTime || 0);
      } else if (newVal == 4) {
        emit("countdownDone");
      }
    }
  },
  {
    immediate: true,
  }
);

// 定时器-通知
let unsubscribe: any = null; // 定时器通知对象
const lotteryInterval = useEventBus("lottery-v3-interval-emit");
onMounted(() => {
  isShowClaimEnd.value = lotteryStore.$state.chestWlSource.recordStatus == 3;
  // 1. 统一的定时器,通知,组件加载的时候只初始化一次
  if (!unsubscribe) {
    unsubscribe = lotteryInterval.on((val: any) => {
      if (unsubscribeFns && Object.keys(unsubscribeFns).length > 0) {
        Object.keys(unsubscribeFns).forEach((key: any) => {
          const fn = unsubscribeFns[key];
          if (fn && typeof fn === "function") {
            fn(val);
          }
        });
      }
    });
  }
  // 2.
  updateLotteryCountdown();
});

onBeforeUnmount(() => {
  if (unsubscribe) unsubscribe(); // 注销通知
  recordStatus_watch && recordStatus_watch();
});
</script>
<style scoped lang="scss">
.freeCountdown {
  position: fixed;
  z-index: 29;
  // top: 400px;
  bottom: calc(var(--safe-area-inset-bottom) + 80 * 2px);
  right: 15 * 2px;
  &-bg {
    position: relative;
    z-index: 9;
    min-height: 61 * 2px;
    width: 64 * 2px;
  }
}
.content {
  position: absolute;
  top: 26 * 2px;
  right: 0;
  width: 100%;
  min-height: 35 * 2px;
  border-radius: 4 * 2px;
  background: linear-gradient(90deg, #fff1e0 0.07%, #ffedd9 99.93%);
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0px 8px 32px rgba(0, 29, 61, 0.24);
  justify-content: center;
  align-items: flex-end;

  &-languagePt {
    margin-top: 25 * 2px;
  }

  &-receive {
    color: #a15428;
    font-size: 11 * 2px;
    font-weight: 590;
    padding: 1.5 * 2px 6 * 2px;
    border-radius: 100px;
    background: #f9dcbc;
    margin-bottom: 1 * 2px;
  }

  &-countdown {
    justify-content: center;
    margin-bottom: 1 * 2px;
    &-text {
      font-size: 11 * 2px;
      font-weight: 590;
      color: #fff;
      background: linear-gradient(180deg, #f25900 0%, #f5a000 100%);
      border-radius: 4 * 2px;
      padding: 3.5px 1px;
      margin-left: 1 * 2px;
    }
    &-width {
      min-width: 16 * 2px;
      text-align: center;
    }
    &-point {
      font-size: 12 * 2px;
      font-weight: 590;
      color: #f25900;
      height: 16 * 2px;
      line-height: 14 * 2px;
      margin-left: 1 * 2px;
    }
  }
}
</style>
